package com.amiu.autoMybatis;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
//@Component
public class DaoInterceptorHelper<T> {
	private static final Logger logger = Logger.getLogger(DaoInterceptorHelper.class);
	private SqlSession sqlSession;
	
	public SqlSession getSqlSession() {
		return sqlSession;
	}

	private T currentDao;
	private T interceptorDao;
	
	@SuppressWarnings("unchecked")
	public DaoInterceptorHelper(SqlSessionFactory sqlSessionFactory,Class<?> mapperClass){
		this.sqlSession = sqlSessionFactory.openSession();
		this.currentDao = (T) sqlSession.getMapper(mapperClass);
		this.interceptorDao = (T) Proxy.newProxyInstance(
				currentDao.getClass().getClassLoader(), 
				new Class[]{mapperClass},
				new DaoInterceptor());
	}
	
	private class DaoInterceptor implements InvocationHandler{

		@Override
		public Object invoke(Object proxy, Method method, Object[] args)
				throws Throwable {
			// TODO Auto-generated method stub
			try {
				logger.debug(currentDao.getClass().getName()+" Method:["+method.getName()+"] AOP调用");
				Object result = method.invoke(currentDao, args);
				sqlSession.commit();
				return result;
			} catch (Exception e) {
				// TODO: handle exception
				logger.debug(proxy.getClass().getName()+" Method:["+method.getName()+"] Exception:",e);
				sqlSession.rollback();
				throw e;
			}finally{
				sqlSession.close();
			}
		}
		
	}
	
	public T getInterceptorMapper(){
		return this.interceptorDao;
	}
}
